import gradio as gr
import os
import subprocess
from SegmentImage import center_crop_pro , clear_input_folder, clear_output_folder, convert_to_png , center_crop

input_folder = "./input_images"
output_folder = "./output_images"

def process_images(width, height):
    """
    处理图片并返回输出文件夹路径
    """
    try:
        center_crop(input_folder, output_folder, (width, height))
        return "处理完成！输出图片已保存到 output_images 文件夹"
    except Exception as e:
        return f"处理失败: {str(e)}"

def open_folder(folder_path):
    """
    打开指定文件夹
    """
    try:
        os.startfile(folder_path)
        return f"已打开文件夹: {folder_path}"
    except Exception as e:
        return f"无法打开文件夹: {str(e)}"

with gr.Blocks() as demo:
    gr.Markdown("# 图片裁剪处理工具")
    
    with gr.Row():
        with gr.Column():
            gr.Markdown("### 处理前图片预览")
            open_input_btn = gr.Button("打开-待处理图片-文件夹")
            clear_input_btn = gr.Button("清空-待处理图片-文件夹")
            convert_to_png_btn = gr.Button("将待处理图片转换为PNG格式")
        with gr.Column():
            gr.Markdown("### 输入图片参数")
            width_slider = gr.Slider(0, 2048, value=512, label="宽度")
            height_slider = gr.Slider(0, 2048, value=512, label="高度")
        with gr.Column():
            process_btn = gr.Button("开始处理图片",variant="primary")
            gr.Markdown("### 处理后图片预览")
            open_output_btn = gr.Button("打开-输出图片-文件夹")
            clear_output_btn = gr.Button("清空-输出图片-文件夹")

 

    status = gr.Textbox(label="处理状态")
    
    gr.Markdown("### 处理后图片预览")
    output_gallery = gr.Gallery(label="处理后图片预览", height="auto",columns=6)
    
    # 绑定事件
    open_input_btn.click(
        fn=lambda: open_folder(os.path.abspath(input_folder)),
        outputs=status
    )
    
    clear_input_btn.click(
        fn=lambda: clear_input_folder(),
        outputs=status
    )
    
    convert_to_png_btn.click(
        fn=lambda: convert_to_png(input_folder),
        outputs=status
    )
    
    open_output_btn.click(
        fn=lambda: open_folder(os.path.abspath(output_folder)),
        outputs=status
    )
    
    clear_output_btn.click(
        fn=lambda: clear_output_folder(),
        outputs=status
    )
    
    def refresh_output():
        return [os.path.join(output_folder, f) for f in os.listdir(output_folder) if f.endswith((".png", ".jpg", ".jpeg"))]
        
    process_btn.click(
        fn=process_images,
        inputs=[width_slider, height_slider],
        outputs=status
    ).then(
        fn=refresh_output,
        outputs=output_gallery
    )
    
    # 自动加载图片预览
    # demo.load(
    #     fn=lambda: [os.path.join(input_folder, f) for f in os.listdir(input_folder) if f.endswith((".png", ".jpg", ".jpeg"))],
    #     outputs=input_gallery
    # )
    
    demo.load(
        fn=lambda: [os.path.join(output_folder, f) for f in os.listdir(output_folder) if f.endswith((".png", ".jpg", ".jpeg"))],
        outputs=output_gallery
    )

if __name__ == "__main__":
    demo.launch()